<link rel="stylesheet" href="nepadmin/lay/extends/treeSelect/css/metroGreen.css">
<style type="text/css">
    .layui-laydate-content>.layui-laydate-list {
        padding-bottom: 0px;
        overflow: hidden;
    }
    .layui-laydate-content>.layui-laydate-list>li{
        width:50%
    }
    .merge-box .scrollbox .merge-list {
        padding-bottom: 5px;
    }
</style>

<div class="layui-fluid" lay-title="请假表单">
    <div class="layui-card">
        <div class="layui-card-body" style="padding: 15px;">
            <form class="layui-form" action="" lay-filter="form-group">
                <div class="layui-form-item">
                    <label class="layui-form-label">请假类型</label>
                    <div id="leaveType">

                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">开始时间</label>
                    <div class="layui-input-block">
                        <input type="text" id="startTime" name="startTime" lay-verify="required" autocomplete="off" placeholder="请输入开始时间" class="layui-input">
                    </div>
                </div>
                <div class="layui-form-item">
                    <label class="layui-form-label">结束时间</label>
                    <div class="layui-input-block">
                        <input type="text" id="endTime" name="endTime" lay-verify="required" autocomplete="off" placeholder="请输入结束时间" class="layui-input">
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label">请假理由</label>
                    <div class="layui-input-block">
                        <textarea placeholder="请输入请假理由" name="content" class="layui-textarea"></textarea>
                    </div>
                </div>

                <div style="display: none" id="taskListShow">
                    <fieldset class="layui-elem-field layui-field-title">
                        <legend style="font-size:14px" id="taskNodeTitle">办理信息</legend>
                    </fieldset>

                </div>

                <!-- 办理人 -->
                <div style="display: none;" id="taskUserShow">

                </div>

                <div class="layui-form-item">
                    <div class="layui-input-block">
                        <button class="layui-btn" lay-submit="" lay-filter="form-group-submit">立即提交</button>
                        <button type="reset" class="layui-btn layui-btn-primary">重置</button>
                    </div>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
    layui.use(['jquery', 'admin', 'form','layer','laydate','selectN','moment','treeSelectP'], function () {
        var $ = layui.jquery
            ,treeSelectP = layui.treeSelectP
            , layer = layui.layer
            , form = layui.form
            , selectN = layui.selectN
            , laydate = layui.laydate
            , admin = layui.admin;
        var table = POPUP_DATA.table;
        var staffSelect = null;
        var activitiNodeList =[];

        var moment = layui.moment;
        //开始日期
        var insStart = laydate.render({
            elem: '#startTime'
            ,type: 'datetime'
            ,format: 'yyyy-MM-dd HH:mm'
            //,value: new Date()
            ,ready: formatminutes
            ,done: function(value, date){
                //更新结束日期的最小日期
                insEnd.config.min = lay.extend({}, date, {
                    month: date.month - 1
                });
                //自动弹出结束日期的选择器
                insEnd.config.elem[0].focus();
            }
        });

        //结束日期
        var insEnd = laydate.render({
            elem: '#endTime'
            ,type: 'datetime'
            ,format: 'yyyy-MM-dd HH:mm'
            ,ready: formatminutes
            ,done: function(value, date){
                //更新开始日期的最大日期
                insStart.config.max = lay.extend({}, date, {
                    month: date.month - 1
                });
                // 计算时长
                // var day = date.date;
                // console.log(date);
                // console.log(insStart.config.dateTime);
                var a = moment(date);
                var insDate = insStart.config.dateTime
                var b = moment(insDate);
                var day = a.diff(b, 'days');
                console.log(day-31);
                var data = {
                    "processId" : "leaveProcess:1:10",
                    "params" : {"day" : day-31}
                };
                startTask(data,day-31);
                form.render(null, 'form-group');
            }
        });
        // 请假类型
        var typeSelect = null;
        admin.get({
            type: 'get',
            url: '/sysDictData/list?dictType=leaveType',
            dataType: 'json',
            success: function(data){
                var selected = [];
                // selected.push(dictType);
                //多选标签-所有配置
                typeSelect = selectN({
                    //元素容器【必填】
                    elem: '#leaveType'
                    ,search:[false,true]
                    //候选数据【必填】
                    ,selected: selected
                    ,data: data.list
                    ,autoWidth:true
                    ,last:true
                    ,field:{idName:'value',titleName:'name'}
                });
            }
        });
        // 获取开始流程信息,传参获取，数据格式{processId:"",params:{}}
        var data = {
            "processId" : "leaveProcess:1:10",
            "params" : {"day" : 0}
        };
        startTask(data);
        form.render(null, 'form-group');

        form.on('submit(form-group-submit)', function (data) {
            var field = data.field;
            var leaveData = {};
            var url = "/oa/leave/save";
            leaveData.applyType = typeSelect.values.join(",");
            leaveData.name = field.name;
            leaveData.startTime = field.startTime;
            leaveData.endTime = field.endTime;
            leaveData.content = field.content;
            // 使用选择器
            var assigneeArr = [];
            $(".laytreelabel").each(function () {
                var id = $(this).attr("data-id");
                assigneeArr.push(id);
            });
            leaveData.assignee = assigneeArr.join(",");
            admin.post({
                url: url,
                contentType: "application/json",
                data: JSON.stringify(leaveData),
                success: function (res) {
                    if (res.code == 0) {
                        // 提醒保存成功，关闭当前弹窗
                        layer.msg(res.msg);
                        layer.closeAll();
                        //刷新
                        table.reload('list-table-taskching', {
                            url: '/activiti/taskCheckingPage?token=' + admin.loginToken,
                            page: {
                                curr: 1
                            }
                        })
                    } else {
                        layer.msg(res.msg);
                    }
                }
            });
            return false;
        });

        // 去除时间选择器中的秒
        function formatminutes(date) {
            var aa = $(".laydate-time-list li ol")[1];
            var showtime = $($(".laydate-time-list li ol")[1]).find("li");
            for (var i = 0; i < showtime.length; i++) {
                var t00 = showtime[i].innerText;
                if (t00 != "00" && t00 != "20" && t00 != "30" && t00 != "40" && t00 != "50") {
                    showtime[i].remove()
                }
            }
            $($(".laydate-time-list li ol")[2]).find("li").remove();  //清空秒
        }
        // 获取开始流程，传参
        function startTask(data,day) {
            var paramsStr = JSON.stringify(data);
            admin.get({
                type: 'get',
                url: '/activiti/getFirstTaskNodeList?params='+encodeURIComponent(paramsStr),
                async:false,
                success: function(data){
                    if (data.code == 0){
                        activitiNodeList = data.activitiNodeList;
                        if (activitiNodeList != null && activitiNodeList.length > 0) {
                            var str='<div class="layui-form-item">\
                                    <label class="layui-form-label">流程步骤</label>\
                                    <div class="layui-input-block">';
                            for(var i = 0,len=activitiNodeList.length; i < len; i++) {
                                var activitiNode = activitiNodeList[i];
                                if (i==0){
                                    var condition="";
                                    if (activitiNode.condition) {
                                        condition = activitiNode.condition;
                                    }
                                    str+='<input type="radio" name="result" lay-filter="result" value="'+condition+'" title="'+activitiNode.name+'" checked="">';
                                } else {
                                    str+='<input type="radio" name="result" lay-filter="result" value="'+condition+'" title="'+activitiNode.name+'" >';
                                }
                            }
                            str+='</div></div>';
                            $("#taskListShow").html(str);
                            $("#taskListShow").show();
                            // 判断第一个是否有数据切换
                            var activitiUserList = activitiNodeList[0].activitiUserList;
                            // 判断是否流程结束
                            if (activitiNodeList.length == 1 && activitiNodeList[0].isLastTask) {
                                console.log("流程结束");
                            } else if (activitiUserList != null && activitiUserList.length > 0) {
                                candidate(activitiUserList);
                            } else {
                                var str='<div class="layui-form-item">\
                                    <label class="layui-form-label">办理人</label>\
                                    <div class="layui-input-block">\
                                    <input type="text" id="tree" name="tree" lay-filter="tree" autocomplete="off" placeholder="请选择办理人"\
                                        class="layui-input">\
                                    </div>\
                                    </div>';
                                $("#taskUserShow").html(str);
                                $("#taskUserShow").show();
                                loadDeptUserTrees();
                            }
                        }
                    }
                }
            });
        }
        // 候选人,data结构[{id:"",name:""}]
        function candidate(data) {
            var str='<div class="layui-form-item">\
                            <label class="layui-form-label">办理人</label>\
                            <div id="assignee">\
                            </div>\
                            </div>';
            $("#taskUserShow").html(str);
            //多选标签-所有配置
            staffSelect = selectN({
                //元素容器【必填】
                elem: '#assignee'
                ,search:[false,true]
                //候选数据【必填】
                ,selected: []
                ,data: data
                ,autoWidth:true
                ,last:true
                ,field:{idName:'id',titleName:'name'}
            });
            $("#taskUserShow").show();
        }
        // 加载组织人员树，多选
        function loadDeptUserTrees(){
            var setting = {
                view: {
                    selectedMulti: true
                },
                check: {
                    enable: true
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pid",
                        rootPId: "0"
                    }
                },

            }
            treeSelectP.render({
                // 选择器
                elem: '#tree',
                // 数据
                data: '/sysUser/listTree?token=' + admin.loginToken,
                // 异步加载方式：get/post，默认get
                type: 'get',
                // 占位符
                placeholder: '请输入搜索关键字',
                // 是否开启搜索功能：true/false，默认false
                search: true,
                // 是否开始只有子节点显示
                isLeaf: true,
                setting: setting,
                // 点击回调
                click: function(d) {
                    //$("#tree").val(d.current.id);
                },
                check: function(d) {

                },
                // 加载完成后的回调函数
                success: function(d) {

                }
            });
        }
        function loadDeptUserTree(){
            var setting = {
                view: {
                    selectedMulti: false
                },
                check: {
                    enable: false
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: "pid",
                        rootPId: "0"
                    }
                },

            }
            treeSelectP.render({
                // 选择器
                elem: '#tree',
                // 数据
                data: '/sysUser/listTree?token=' + admin.loginToken,
                // 异步加载方式：get/post，默认get
                type: 'get',
                // 占位符
                placeholder: '请输入搜索关键字',
                // 是否开启搜索功能：true/false，默认false
                search: true,
                // 是否开始只有子节点显示
                isLeaf: true,
                setting: setting,
                // 点击回调
                click: function(d) {
                    //$("#tree").val(d.current.id);
                },
                check: function(d) {

                },
                // 加载完成后的回调函数
                success: function(d) {

                }
            });
        }
    });
</script>